package me.imli.app.dao;

import java.util.ArrayList;
import java.util.List;

import me.imli.app.model.RssFeedModel;
import me.imli.app.util.db.Column;
import me.imli.app.util.db.SQLiteTable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.provider.BaseColumns;

public class RssDataHelper extends BaseDataHelper {

	public RssDataHelper(Context context) {
		super(context);
	}

	@Override
	protected Uri getContentUri() {
		return DataProvider.RSS_CONTENT_URI;
	}
	
    private ContentValues getContentValues(RssFeedModel model) {
        ContentValues values = new ContentValues();
        values.put(RssDBInfo.ID, model.link);
        values.put(RssDBInfo.JSON, model.toJson());
        return values;
    }
    
    public RssFeedModel query() {
    	RssFeedModel model = null;
        Cursor cursor = query(null, null, null, null);
        if (cursor.moveToFirst()) {
        	model = RssFeedModel.fromCursor(cursor);
        }
        cursor.close();
        return model;
    }
    
    public void insert(RssFeedModel model) {
        insert(getContentValues(model));
    }
    
    public void bulkInsert(List<RssFeedModel> models) {
        ArrayList<ContentValues> contentValueses = new ArrayList<ContentValues>();
        for (RssFeedModel model : models) {
            ContentValues values = getContentValues(model);
            contentValueses.add(values);
        }
        ContentValues[] valueArray = new ContentValues[contentValueses.size()];
        bulkInsert(contentValueses.toArray(valueArray));
    }

    public int deleteAll() {
        synchronized (DataProvider.DBLock) {
            DBHelper mDbHelper = DataProvider.getDBHelper();
            SQLiteDatabase db = mDbHelper.getWritableDatabase();
            int row = db.delete(RssDBInfo.TABLE_NAME, null, null);
            return row;
        }
    }
    
    public static final class RssDBInfo implements BaseColumns {

        /** 表名 */
        public static final String TABLE_NAME = "rss";

        /** ID */
        public static final String ID = "id";

        /** JSON */
        public static final String JSON = "json";

        public static final SQLiteTable TABLE = new SQLiteTable(TABLE_NAME)
                .addColumn(ID, Column.DataType.INTEGER)
                .addColumn(JSON, Column.DataType.TEXT);
    }

}
